<template>
	<view class="container">
		<!-- 页面头部 -->
		<view class="header">
			<view class="header-content">
				<view class="title-section">
					<text class="page-title">已完成事项</text>
					<text class="page-desc">共 {{ completedSchedules.length }} 个已完成事项</text>
				</view>
				<view class="action-section">
					<button class="clear-btn" @click="clearAllCompleted" v-if="completedSchedules.length > 0">
						<uni-icons type="trash" size="16" color="#EF4444" />
						<text class="clear-text">清空</text>
					</button>
				</view>
			</view>
		</view>

		<!-- 筛选栏 -->
		<view class="filter-bar">
			<view class="filter-row">
				<!-- 显示状态筛选 -->
				<view class="filter-group">
					<view class="filter-label">显示状态</view>
					<picker 
						:value="getPickerIndex('visibility')" 
						:range="visibilityOptions"
						range-key="label"
						@change="onVisibilityChange"
						class="filter-picker"
					>
						<view class="picker-display">
							{{ getCurrentLabel('visibility') }}
							<uni-icons type="bottom" size="14" color="#6B7280" />
						</view>
					</picker>
				</view>
				
				<!-- 类型筛选 -->
				<view class="filter-group">
					<view class="filter-label">类型</view>
					<picker 
						:value="getPickerIndex('type')" 
						:range="typeOptions"
						range-key="label"
						@change="onTypeChange"
						class="filter-picker"
					>
						<view class="picker-display">
							{{ getCurrentLabel('type') }}
							<uni-icons type="bottom" size="14" color="#6B7280" />
						</view>
					</picker>
				</view>
				
				<!-- 优先级筛选 -->
				<view class="filter-group">
					<view class="filter-label">优先级</view>
					<picker 
						:value="getPickerIndex('priority')" 
						:range="priorityOptions"
						range-key="label"
						@change="onPriorityChange"
						class="filter-picker"
					>
						<view class="picker-display">
							{{ getCurrentLabel('priority') }}
							<uni-icons type="bottom" size="14" color="#6B7280" />
						</view>
					</picker>
				</view>
			</view>
		</view>

		<!-- 已完成事项列表 -->
		<view class="schedule-list">
			<view v-if="filteredCompletedSchedules.length === 0" class="empty-state">
				<uni-icons type="checkmarkempty" size="64" color="#D1D5DB" />
				<text class="empty-text">暂无已完成事项</text>
				<text class="empty-desc">完成的事项会显示在这里</text>
			</view>
			
			<view v-else>
				<view 
					v-for="schedule in filteredCompletedSchedules" 
					:key="schedule.id"
					class="completed-card"
					:class="{ hidden: isHidden(schedule.id) }"
				>
					<!-- 卡片内容 -->
					<view class="card-content">
						<!-- 头部：标题和状态 -->
						<view class="card-header">
							<view class="title-section">
								<text class="schedule-title completed">{{ schedule.title }}</text>
								<view class="status-badges">
									<view class="type-badge" :class="schedule.type">
										<text class="type-text">{{ schedule.type === 'task' ? '任务' : '日程' }}</text>
									</view>
									<view class="priority-badge" :class="`priority-${schedule.priority}`">
										<text class="priority-text">{{ getPriorityText(schedule.priority) }}</text>
									</view>
									<view class="hidden-badge" v-if="isHidden(schedule.id)">
										<text class="hidden-text">已隐藏</text>
									</view>
								</view>
							</view>
							
							<view class="action-section">
								<uni-icons type="checkmarkempty" size="20" color="#10B981" />
							</view>
						</view>
						
						<!-- 描述 -->
						<view class="description" v-if="schedule.description">
							<text class="description-text">{{ schedule.description }}</text>
						</view>
						
						<!-- 时间信息 -->
						<view class="time-info" v-if="schedule.type !== 'task'">
							<uni-icons type="calendar" size="14" color="#10B981" />
							<text class="time-text">{{ formatTime(schedule.endTime) }}</text>
						</view>
						
						<!-- 完成时间 -->
						<view class="completed-info">
							<uni-icons type="clock" size="14" color="#6B7280" />
							<text class="completed-text">完成于 {{ formatCompletedTime(schedule.updatedAt) }}</text>
						</view>
					</view>
					
					<!-- 操作按钮 -->
					<view class="card-actions">
						<button 
							class="action-btn restore-btn" 
							@click="toggleVisibility(schedule.id)"
						>
							<uni-icons 
								:type="isHidden(schedule.id) ? 'eye' : 'eye-slash'" 
								size="16" 
								color="#FFFFFF" 
							/>
							<text class="action-text">{{ isHidden(schedule.id) ? '显示' : '隐藏' }}</text>
						</button>
						<button class="action-btn undo-btn" @click="undoCompleted(schedule.id)">
							<uni-icons type="undo" size="16" color="#FFFFFF" />
							<text class="action-text">撤销</text>
						</button>
						<button class="action-btn delete-btn" @click="deleteSchedule(schedule.id)">
							<uni-icons type="trash" size="16" color="#FFFFFF" />
							<text class="action-text">删除</text>
						</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
	name: 'CompletedPage',
	
	data() {
		return {
			filters: {
				visibility: 'all', // all, visible, hidden
				type: 'all', // all, schedule, task
				priority: 'all' // all, urgent, high, medium, low
			},
			// 下拉选项数据
			visibilityOptions: [
				{ value: 'all', label: '全部' },
				{ value: 'visible', label: '显示中' },
				{ value: 'hidden', label: '已隐藏' }
			],
			typeOptions: [
				{ value: 'all', label: '全部' },
				{ value: 'schedule', label: '日程' },
				{ value: 'task', label: '任务' }
			],
			priorityOptions: [
				{ value: 'all', label: '全部' },
				{ value: 'urgent', label: '紧急' },
				{ value: 'high', label: '高' },
				{ value: 'medium', label: '中' },
				{ value: 'low', label: '低' }
			]
		}
	},
	
	computed: {
		...mapState('schedule', ['hiddenCompletedSchedules']),
		...mapGetters('schedule', ['completedSchedules']),
		
		// 过滤后的已完成事项
		filteredCompletedSchedules() {
			let schedules = this.completedSchedules
			
			// 按显示状态过滤
			if (this.filters.visibility !== 'all') {
				if (this.filters.visibility === 'visible') {
					schedules = schedules.filter(schedule => !this.isHidden(schedule.id))
				} else if (this.filters.visibility === 'hidden') {
					schedules = schedules.filter(schedule => this.isHidden(schedule.id))
				}
			}
			
			// 按类型过滤
			if (this.filters.type !== 'all') {
				schedules = schedules.filter(schedule => 
					(schedule.type || 'schedule') === this.filters.type
				)
			}
			
			// 按优先级过滤
			if (this.filters.priority !== 'all') {
				schedules = schedules.filter(schedule => schedule.priority === this.filters.priority)
			}
			
			return schedules
		}
	},
	
	async onLoad() {
		// 加载数据
		await this.loadSchedules()
	},
	
	methods: {
		...mapActions('schedule', ['loadSchedules', 'toggleCompleted', 'deleteSchedule']),
		
		// 检查事项是否被隐藏
		isHidden(scheduleId) {
			return this.hiddenCompletedSchedules.includes(scheduleId)
		},
		
		// 切换显示/隐藏状态
		toggleVisibility(scheduleId) {
			this.$store.commit('schedule/TOGGLE_HIDDEN_SCHEDULE', scheduleId)
			const isNowHidden = this.isHidden(scheduleId)
			uni.showToast({
				title: isNowHidden ? '已隐藏' : '已显示',
				icon: 'success',
				duration: 1500
			})
		},
		
		// 撤销完成状态
		async undoCompleted(scheduleId) {
			uni.showModal({
				title: '确认撤销',
				content: '确定要撤销这个事项的完成状态吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							// 从隐藏列表中移除
							this.$store.commit('schedule/SHOW_COMPLETED_SCHEDULE', scheduleId)
							// 切换完成状态
							await this.toggleCompleted(scheduleId)
							uni.showToast({
								title: '已撤销完成',
								icon: 'success'
							})
						} catch (error) {
							uni.showToast({
								title: '操作失败',
								icon: 'error'
							})
						}
					}
				}
			})
		},
		
		// 删除事项
		async deleteSchedule(scheduleId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要永久删除这个事项吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							// 从隐藏列表中移除
							this.$store.commit('schedule/SHOW_COMPLETED_SCHEDULE', scheduleId)
							// 删除事项
							await this.$store.dispatch('schedule/deleteSchedule', scheduleId)
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
						} catch (error) {
							uni.showToast({
								title: '删除失败',
								icon: 'error'
							})
						}
					}
				}
			})
		},
		
		// 清空所有已完成事项
		clearAllCompleted() {
			uni.showModal({
				title: '确认清空',
				content: `确定要删除所有 ${this.completedSchedules.length} 个已完成事项吗？此操作不可恢复。`,
				success: async (res) => {
					if (res.confirm) {
						try {
							const completedIds = this.completedSchedules.map(s => s.id)
							// 批量删除
							await this.$store.dispatch('schedule/batchDelete', completedIds)
							// 清空隐藏列表
							this.$store.state.schedule.hiddenCompletedSchedules = []
							uni.showToast({
								title: '清空成功',
								icon: 'success'
							})
						} catch (error) {
							uni.showToast({
								title: '清空失败',
								icon: 'error'
							})
						}
					}
				}
			})
		},
		
		// 获取当前筛选值对应的选项索引
		getPickerIndex(type) {
			const options = this[`${type}Options`]
			const currentValue = this.filters[type]
			return options.findIndex(option => option.value === currentValue)
		},
		
		// 获取当前筛选值对应的显示标签
		getCurrentLabel(type) {
			const options = this[`${type}Options`]
			const currentValue = this.filters[type]
			const option = options.find(option => option.value === currentValue)
			return option ? option.label : '全部'
		},
		
		// 显示状态改变事件
		onVisibilityChange(e) {
			const index = e.detail.value
			const value = this.visibilityOptions[index].value
			this.filters.visibility = value
		},
		
		// 类型改变事件
		onTypeChange(e) {
			const index = e.detail.value
			const value = this.typeOptions[index].value
			this.filters.type = value
		},
		
		// 优先级改变事件
		onPriorityChange(e) {
			const index = e.detail.value
			const value = this.priorityOptions[index].value
			this.filters.priority = value
		},
		
		// 格式化时间显示
		formatTime(timeString) {
			const date = new Date(timeString)
			const now = new Date()
			const diffDays = Math.ceil((date - now) / (1000 * 60 * 60 * 24))
			
			// 今天
			if (diffDays === 0) {
				return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			}
			// 明天
			else if (diffDays === 1) {
				return `明天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			}
			// 昨天
			else if (diffDays === -1) {
				return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			}
			// 其他日期
			else {
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')
				return `${month}/${day} ${hours}:${minutes}`
			}
		},
		
		// 格式化完成时间
		formatCompletedTime(timeString) {
			const date = new Date(timeString)
			const now = new Date()
			const diffMs = now - date
			const diffMinutes = Math.floor(diffMs / (1000 * 60))
			const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
			const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
			
			if (diffMinutes < 1) {
				return '刚刚'
			} else if (diffMinutes < 60) {
				return `${diffMinutes}分钟前`
			} else if (diffHours < 24) {
				return `${diffHours}小时前`
			} else if (diffDays < 7) {
				return `${diffDays}天前`
			} else {
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				return `${month}/${day}`
			}
		},
		
		// 获取优先级文本
		getPriorityText(priority) {
			const map = {
				'urgent': '紧急',
				'high': '高',
				'medium': '中',
				'low': '低'
			}
			return map[priority] || '中'
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: $background-gray;
}

.header {
	background-color: $card-white;
	border-bottom: 1px solid $border-gray;
	padding: $spacing-lg;
}

.header-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.title-section {
	flex: 1;
}

.page-title {
	font-size: $font-size-title-1;
	font-weight: $font-weight-bold;
	color: $text-dark-gray;
	display: block;
	margin-bottom: $spacing-xs;
}

.page-desc {
	font-size: $font-size-caption;
	color: $text-light-gray;
}

.action-section {
	flex-shrink: 0;
}

.clear-btn {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	padding: $spacing-sm $spacing-md;
	background-color: transparent;
	border: 1px solid #FEE2E2;
	border-radius: $border-radius-md;
	font-size: $font-size-caption;
	
	&:active {
		background-color: #FEE2E2;
	}
}

.clear-text {
	color: #EF4444;
	font-size: $font-size-caption;
}

.filter-bar {
	background-color: $card-white;
	border-bottom: 1px solid $border-gray;
	padding: $spacing-lg;
}

.filter-row {
	display: flex;
	gap: $spacing-md;
	align-items: flex-end;
}

.filter-group {
	flex: 1;
	min-width: 0;
}

.filter-label {
	font-size: $font-size-caption;
	color: $text-light-gray;
	margin-bottom: $spacing-xs;
	font-weight: 500;
}

.filter-picker {
	width: 100%;
}

.picker-display {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: $spacing-sm $spacing-md;
	background-color: $background-gray;
	border-radius: $border-radius-md;
	border: 1px solid $border-gray;
	font-size: $font-size-body;
	color: $text-dark-gray;
	height: 40px;
	transition: all 0.2s ease;
	
	&:active {
		background-color: #F3F4F6;
		border-color: $primary-blue;
	}
}

.schedule-list {
	padding: $spacing-lg;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px $spacing-lg;
	text-align: center;
}

.empty-text {
	margin-top: $spacing-lg;
	font-size: $font-size-title-2;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
}

.empty-desc {
	margin-top: $spacing-sm;
	font-size: $font-size-body;
	color: $text-light-gray;
}

.completed-card {
	background-color: $card-white;
	border-radius: $border-radius-md;
	margin-bottom: $spacing-md;
	overflow: hidden;
	box-shadow: $shadow-sm;
	border-left: 4px solid #10B981;
	
	&.hidden {
		opacity: 0.6;
		border-left-color: #6B7280;
	}
}

.card-content {
	padding: $spacing-lg;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: $spacing-sm;
}

.title-section {
	flex: 1;
	margin-right: $spacing-md;
}

.schedule-title {
	font-size: $font-size-title-2;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
	line-height: $line-height-title-2;
	display: block;
	margin-bottom: $spacing-xs;
	
	&.completed {
		text-decoration: line-through;
		color: #10B981;
	}
}

.status-badges {
	display: flex;
	flex-wrap: wrap;
	gap: $spacing-xs;
}

.type-badge, .priority-badge, .hidden-badge {
	padding: 2px $spacing-sm;
	border-radius: $border-radius-lg;
	font-size: $font-size-caption;
}

.type-badge {
	&.task {
		background-color: #E0F2FE;
		.type-text { color: #0891B2; }
	}
	
	&.schedule {
		background-color: #F3E8FF;
		.type-text { color: #7C3AED; }
	}
}

.priority-badge {
	&.priority-urgent {
		background-color: $urgent-light-red;
		.priority-text { color: $urgent-red; }
	}
	
	&.priority-high {
		background-color: $high-light-orange;
		.priority-text { color: $high-orange; }
	}
	
	&.priority-medium {
		background-color: $medium-light-purple;
		.priority-text { color: $medium-purple; }
	}
	
	&.priority-low {
		background-color: $low-light-gray;
		.priority-text { color: $low-gray; }
	}
}

.hidden-badge {
	background-color: #F3F4F6;
	.hidden-text { color: #6B7280; }
}

.action-section {
	flex-shrink: 0;
}

.description {
	margin-bottom: $spacing-md;
}

.description-text {
	font-size: $font-size-body;
	color: $text-light-gray;
	line-height: $line-height-body;
}

.time-info, .completed-info {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	margin-bottom: $spacing-xs;
}

.time-text, .completed-text {
	font-size: $font-size-caption;
	color: #6B7280;
}

.card-actions {
	display: flex;
	gap: $spacing-sm;
	padding: $spacing-md;
	background-color: #F9FAFB;
	border-top: 1px solid $border-gray;
}

.action-btn {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	padding: $spacing-sm $spacing-md;
	border-radius: $border-radius-md;
	border: none;
	font-size: $font-size-caption;
	flex: 1;
	justify-content: center;
	
	&.restore-btn {
		background-color: $primary-blue;
	}
	
	&.undo-btn {
		background-color: #F59E0B;
	}
	
	&.delete-btn {
		background-color: $urgent-red;
	}
	
	&:active {
		transform: scale(0.95);
	}
}

.action-text {
	color: #FFFFFF;
	font-size: $font-size-caption;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.filter-row {
		gap: $spacing-xs;
	}
	
	.filter-label {
		font-size: 11px;
		margin-bottom: 4px;
	}
	
	.picker-display {
		padding: 6px $spacing-xs;
		height: 36px;
		font-size: 12px;
	}
	
	.card-actions {
		flex-direction: column;
		gap: $spacing-xs;
	}
	
	.action-btn {
		padding: $spacing-sm;
	}
}
</style> 